#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010,SC3015 source=/dev/null
#
# Start watchdog
#

case "$1" in
  start)
    # no /dev/watchdog device, no watchdog daemon startup
    if [[ -c /dev/watchdog ]]; then
      # source /VERSION to get PLATFORM
      [[ -r /VERSION ]] && . /VERSION

      # do not start watchdog daemon on docker/lxc envs
      if [[ ! "${PLATFORM}" =~ oci\|lxc ]]; then
        echo "Starting watchdog..."
        /sbin/watchdog -T 300 -t 5 /dev/watchdog
      fi
    fi

    # to identify unexpected crashes/shutdowns we check
    # for a /usr/local/tmp/.watchdog file to be
    # present and if so we set /var/status/uncleanShutdown
    # to signal this to others.
    if [[ -f /usr/local/tmp/.watchdog ]]; then

      # make sure /var/status exists with correct permissions
      if [[ ! -d /var/status ]]; then
        mkdir -p /var/status
        chown root:status /var/status
        chmod 2775 /var/status
      fi

      touch /var/status/uncleanShutdown
    else
      mkdir -p /usr/local/tmp
      touch /usr/local/tmp/.watchdog
      sync
    fi
  ;;
  stop)
    # remove /usr/local/tmp/.watchdog
    # to make sure the next boot is identified as a
    # clean boot.
    rm -f /usr/local/tmp/.watchdog
    sync
  ;;
  restart|reload)
  ;;
  *)
  echo "Usage: $0 {start|stop|restart}"
  exit 1
esac

exit 0
